package com.config;

import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Resource
private UserService userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf()//禁用跨域保护策略，默认开启
                .disable()
                .authorizeRequests()//认证需求路径
                .antMatchers("/", "/home")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()//登录路径
                .loginPage("/signin")
                .loginProcessingUrl("/dosignin")
                .failureUrl("/error")
                .defaultSuccessUrl("/hello")
                .permitAll()
                .and()
                .logout()//登出路径
                .logoutSuccessUrl("/home")
                .logoutUrl("/logout");
        }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //用自定义的userDetailsService，并设置一个无加密的加密器
        auth.userDetailsService(userService).passwordEncoder(NoOpPasswordEncoder.getInstance());
        //也可以设置一个BCrypt加密的
        //auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
        //加密器可以用Bean的办法配置，如下方注释部分
    }
//    @Bean
//    PasswordEncoder passwordEncoder(){
//        return new BCryptPasswordEncoder();
//    }


}
